package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 总单数和实际单数统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersReport(LocalDate begin, LocalDate end) {
        //日期数据
        ArrayList<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDates.add(begin);
        }
        //每日订单数
        ArrayList<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        //日期总数据
        for (LocalDate date : localDates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer status = 5;

            HashMap<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);

            Integer orderCount = ordersMapper.ordersReport(map);

            map.put("status", status);
            Integer validOrder = ordersMapper.ordersReport(map);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrder);
        }

        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        //组装vo
        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDates, ","))//日期数据
                .orderCountList(StringUtils.join(orderCountList, ","))//每日总订单数据
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))//每日有效订单数据
                .totalOrderCount(totalOrderCount)//订单总数
                .validOrderCount(validOrderCount)//有效订单数
                .orderCompletionRate(orderCompletionRate)//订单完成率
                .build();
    }

    /**
     * 菜品销量前十
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        // 数据准备 时间数据
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 准备查找数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", Orders.COMPLETED);

        // 将返回结果封装进GoodsSalesDTO，将GoodsSalesDTO对象放进集合
        List<GoodsSalesDTO> goodsSalesDTOS = ordersMapper.top10(map);
        // 把集合中的名称抽取成集合
        List<String> nameList = goodsSalesDTOS.stream().map(
                GoodsSalesDTO::getName
        ).collect(Collectors.toList());
        // 把集合中的销量抽取成集合
        List<Integer> numberList = goodsSalesDTOS.stream().map(
                GoodsSalesDTO::getNumber
        ).collect(Collectors.toList());
        // 组装vo
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 营业额统计图接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 准备时间数据
        ArrayList<LocalDate> localDates = new ArrayList<>();

        localDates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDates.add(begin);
        }
        // 准备营业额数据
        ArrayList<Integer> turnoverList = new ArrayList<>();
        for (LocalDate date : localDates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            HashMap<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);

            Integer turnover = ordersMapper.turnoverStatistics(map);
            turnoverList.add(turnover == null ? 0 : turnover);
        }

        // 组装vo
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(localDates, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户数量统计图接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 准备时间数据
        ArrayList<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDates.add(begin);
        }

        ArrayList<Integer> newUserList = new ArrayList<>();
        ArrayList<Integer> totalUserList = new ArrayList<>();

        // 准备用户数据
        for (LocalDate date : localDates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 总用户
            HashMap<String, Object> map = new HashMap<>();
            map.put("endTime", endTime);
            Integer totalUser = userMapper.userStatistics(map);
            // 新用户
            map.put("beginTime", beginTime);
            Integer newUser = userMapper.userStatistics(map);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        // 组装vo
        return UserReportVO.builder()
                .dateList(StringUtils.join(localDates, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 导出运营数据报表
     */
    @Override
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        // 按照时间 查到找工作台数据
        BusinessDataVO businessData = workspaceService
                .getBusinessData(LocalDateTime.of(begin, LocalTime.MIN),
                        LocalDateTime.of(end, LocalTime.MAX));
        // 拿到流对象
        InputStream is =
                OrderReportVO.class.getClassLoader()
                        .getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook sheets = new XSSFWorkbook(is);
            XSSFSheet sheet = sheets.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + " 至 " + end);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                businessData = workspaceService.getBusinessData(
                        LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            ServletOutputStream outputStream = response.getOutputStream();
            sheets.write(outputStream);

            outputStream.close();
            sheets.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
